package com.jsmile.cloud.authc.sys;

import java.util.List;
import java.util.stream.Collectors;

import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jsmile.cloud.authc.api.req.sys.ReqSysDeptPageQuery;
import com.jsmile.cloud.authc.api.req.sys.ReqSysDeptQuery;
import com.jsmile.cloud.authc.api.req.sys.ReqSysDeptUpdate;
import com.jsmile.cloud.authc.api.res.ResSysDept;
import com.jsmile.cloud.authc.sys.model.SysDepartment;
import com.jsmile.cloud.authc.sys.repo.SysDepartmentRepository;
import com.jsmile.cloud.authc.sys.repo.SysDepartmentSearchRepository;
import com.jsmile.mall.api.exception.ExceptionKit;

import cn.hutool.core.bean.BeanUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
@AllArgsConstructor
public class SysDeptApplicationService {

    private final SysDepartmentSearchRepository sysDepartmentSearchRepository;
    private final SysDepartmentRepository sysDepartmentRepository;

    public IPage<ResSysDept> getPageList(ReqSysDeptPageQuery reqSysDeptQuery) {
        ExceptionKit.checkNotNull(reqSysDeptQuery.getCurTenantId(), "租户id不能为空!");
        log.info("部门查询:{]", reqSysDeptQuery);
        return sysDepartmentSearchRepository.pageQuery(reqSysDeptQuery).convert(x -> BeanUtil.toBean(x, ResSysDept.class));
    }

    public List<ResSysDept> getList(ReqSysDeptQuery reqSysDeptQuery) {
        ExceptionKit.checkNotNull(reqSysDeptQuery.getCurTenantId(), "租户id不能为空!");
        log.info("部门查询:{]", reqSysDeptQuery);
        return sysDepartmentSearchRepository.getList(reqSysDeptQuery).stream().map(x -> BeanUtil.toBean(x, ResSysDept.class)).collect(Collectors.toList());
    }

    public boolean saveDept(ReqSysDeptUpdate reqSysDeptUpdate) {
        reqSysDeptUpdate.setParentId(null == reqSysDeptUpdate.getParentId() ? 0 : reqSysDeptUpdate.getParentId());
        return sysDepartmentRepository.save(SysDepartment.create(reqSysDeptUpdate));
    }

    public boolean updateDept(ReqSysDeptUpdate reqSysDeptUpdate) {
        return sysDepartmentRepository.updateById(SysDepartment.create(reqSysDeptUpdate));
    }

    public boolean deleteDept(ReqSysDeptUpdate reqSysDeptUpdate) {
        sysDepartmentRepository.remove(new UpdateWrapper<SysDepartment>().lambda().eq(SysDepartment::getParentId, reqSysDeptUpdate.getId()));
        return sysDepartmentRepository.removeById(reqSysDeptUpdate.getId());
    }
}
